package ua.kiev.tosik.price.modules.clients.tools;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IPricesFilesDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.PricesFiles;
import ua.kiev.tosik.price.modules.clients.models.ExcelData;

import javax.swing.*;
import java.util.Vector;

public class ExcelParserWorker extends SwingWorker<Vector<ExcelData>, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.tools");
	private ExcelParser parser;
	private PricesFiles pricesFiles;

	public ExcelParserWorker(PricesFiles pricesFiles) {
		super();
		this.pricesFiles = pricesFiles;
		logger.debug("Initialize ExcelParserWorker");
	}

	@Override
	protected Vector<ExcelData> doInBackground() throws Exception {
		if ( pricesFiles == null ) {
			throw new Exception("Record PricesFiles nor defined!");
		}
		firePropertyChange("PARSE_START", null, true);
		if ( pricesFiles.getSourceFile() == null || pricesFiles.getSourceFile().length == 0 ) {
			IPricesFilesDao pricesFilesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesFilesDao();
			pricesFiles.setSourceFile(pricesFilesDao.loadFile(pricesFiles.getId()));
		} else {
			logger.debug("Source file already loaded");
		}
		parser = new ExcelParser(pricesFiles.getSourceFile());
		return parser.parse();
	}

	@Override
	protected void done() {
		super.done();
		firePropertyChange("PARSE_DONE", null, true);
		try {
			Vector<ExcelData> data = get();
			firePropertyChange("PARSE_OK", null, data);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			firePropertyChange("PARSE_ERROR", null, e);
		}
	}
}
